import cv2
import mediapipe as mp

# 初始化 MediaPipe FaceMesh
mp_face_mesh = mp.solutions.face_mesh
mp_drawing = mp.solutions.drawing_utils
mp_styles = mp.solutions.drawing_styles

# 打开摄像头（0 表示默认摄像头）
cap = cv2.VideoCapture(0)

# 使用 FaceMesh（静态模式=否，最多检测1张脸，检测置信度阈值）
with mp_face_mesh.FaceMesh(
        max_num_faces=1,
        refine_landmarks=True,  # 开启眼睛/嘴唇细节关键点
        min_detection_confidence=0.5,
        min_tracking_confidence=0.5) as face_mesh:

    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            print("⚠️ 无法读取摄像头画面")
            break

        # OpenCV 默认是 BGR，MediaPipe 需要 RGB
        rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        # 禁止写入（提升性能）
        rgb_frame.flags.writeable = False
        results = face_mesh.process(rgb_frame)

        # 转回可写模式
        rgb_frame.flags.writeable = True
        frame = cv2.cvtColor(rgb_frame, cv2.COLOR_RGB2BGR)

        # 如果检测到人脸
        if results.multi_face_landmarks:
            for face_landmarks in results.multi_face_landmarks:
                # 绘制关键点（468个点）
                mp_drawing.draw_landmarks(
                    image=frame,
                    landmark_list=face_landmarks,
                    connections=mp_face_mesh.FACEMESH_TESSELATION,
                    landmark_drawing_spec=None,
                    connection_drawing_spec=mp_styles.get_default_face_mesh_tesselation_style()
                )
                # 绘制眼睛、嘴巴等特征线
                mp_drawing.draw_landmarks(
                    image=frame,
                    landmark_list=face_landmarks,
                    connections=mp_face_mesh.FACEMESH_CONTOURS,
                    landmark_drawing_spec=None,
                    connection_drawing_spec=mp_styles.get_default_face_mesh_contours_style()
                )

        # 显示画面
        cv2.imshow('FaceMesh Demo', frame)

        # 按 ESC 退出
        if cv2.waitKey(5) & 0xFF == 27:
            break

cap.release()
cv2.destroyAllWindows()